package cn.hznc.excel;

import cn.hznc.dto.AllotEmployeeImport;
import cn.hznc.dto.FirstStockImport;
import cn.hznc.exception.SystemEx;
import cn.hznc.exception.SystemException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author：Administrator
 * @Date：2023/10/8 14:26
 */
@Slf4j
public class FirstCabinetStockReadListener implements ReadListener<FirstCabinetStockImport>{
    /**
     * 1000条数据存入数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;


    /**
     * 缓存的数据
     */
    private List<FirstCabinetStockImport> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public FirstCabinetStockReadListener() {

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (cachedDataList.size() > BATCH_COUNT) {
            throw new SystemException(SystemEx.FILE_EXCEL_MAX_COLUMN_ERROR.getCode(),SystemEx.FILE_EXCEL_MAX_COLUMN_ERROR.getMsg());
        }
        throw exception;
    }

    @Override
    public void invoke(FirstCabinetStockImport firstCabinetStockImport, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(firstCabinetStockImport));
        cachedDataList.add(firstCabinetStockImport);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 获取导入数据
     *
     * @return
     */
    public List<FirstCabinetStockImport> getImportData(){
        return cachedDataList;
    }
}
